package cn.doitedu;

import cn.hutool.core.date.DateUtil;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.BytesWritable;
import org.roaringbitmap.longlong.Roaring64Bitmap;

import java.io.IOException;
import java.util.Date;

/**
 * @Author: 深似海
 * @Site: <a href="www.51doit.com">多易教育</a>
 * @QQ: 657270652
 * @Date: 2024/4/26
 * @Desc: 学大数据，上多易教育
 * 求一个bitmap中最后一个或第一个活跃日期
 **/
public class BitmapGetLastOrFirstActiveDate extends UDF {

    private static final Date INITIAL = DateUtil.parse("2000-01-01");

    public String evaluate(BytesWritable bitmapBytesWritable, boolean isFirst) throws IOException {
        // 反序列化出bitmap对象
        Roaring64Bitmap bm = BitmapUtils.de(bitmapBytesWritable.getBytes());

        // 求受访日

        if (isFirst) {
            try {
                long between = bm.first();
                return DateUtil.format(DateUtil.offsetDay(INITIAL, (int) between), "yyyy-MM-dd");

            } catch (Exception e) {
                return null;
            }
        }else{
            try {
                long between = bm.last();
                return DateUtil.format(DateUtil.offsetDay(INITIAL, (int) between), "yyyy-MM-dd");

            } catch (Exception e) {
                return null;
            }
        }


    }

}
